package com.applink.sell_proof.builder;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;

/**
 * 
 * @author update by Van Vu
 * 
 */
public abstract class AbstractBuilder {

	protected BaseAdapter mAdapter;
	protected ViewGroup mParentView;
	protected LayoutInflater mLayoutInflater;
	protected volatile List<? extends Object> mData;
	protected Context mContext;

	// Constructor
	public AbstractBuilder(Context context, ViewGroup parent) {
		// the parent view of the builder
		mParentView = parent;

		// the layout inflater (layout render)
		mLayoutInflater = LayoutInflater.from(context);

		// data of the list
		mData = new ArrayList<Object>();

		// context object
		mContext = context;

		// assign the adapter obj
		mAdapter = getAdapter();
	}

	// Internal build product

	public abstract void buildData();

	/**
	 * 
	 * Inflate the convertView which would be reused as parameter in extend
	 * BaseAdapter implementation. If you override the getView method of the
	 * BaseAdapter, you're going to initialize the View object of 1 item in the
	 * first place anyway and reused it for later (only data was changed)
	 * 
	 * @return
	 */
	public abstract View buildConvertView();

	/**
	 * 
	 * Each list element item will come with many other sub views such as
	 * images, button. An implementation of this method will generate a
	 * collection of all the sub views of ConvertView and be ready for reused.
	 * 
	 * @param base
	 * @return
	 */
	public abstract ConcurrentHashMap<Integer, View> buildConvertViewContent(
			View base);

	/**
	 * 
	 * Build data associate with an item on the list
	 * 
	 * @param position
	 * @param views
	 * @param data
	 */
	public abstract void builConvertViewContentData(int position,
			ConcurrentHashMap<Integer, View> views, List<? extends Object> data);

	/**
	 * 
	 * return/initialize if empty the current Adapter object for current
	 * ListView
	 * 
	 * @author Van Vu
	 * @return
	 */
	protected abstract BaseAdapter getAdapter();

	public List<? extends Object> getData() {
		return mData;
	}

	public void setData(List<? extends Object> data) {
		View loading = mParentView
				.findViewById(com.applink.sell_proof.R.id.pb_loading);
		if (loading != null)
			loading.setVisibility(View.GONE);
		synchronized (mData) {
			mData.clear();
			if (data != null) {
				mData = data;
				mAdapter.notifyDataSetChanged();
			}
		}
	}

	public void clear() {
		synchronized (mData) {
			mData.clear();
		}
	}
}
